package com.cays.myresearch.activity;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.cays.myresearch.R;
import com.cays.myresearch.Util.HttpUtil;
import com.cays.myresearch.action.LoginAction;
import com.cays.myresearch.constant.Constant;
import com.cays.myresearch.entity.Question;
import com.cays.myresearch.entity.QuestionAnswer;
import com.cays.myresearch.entity.ResponseInfo;
import com.cays.myresearch.entity.Student;
import com.cays.myresearch.entity.Teacher;
import com.cays.myresearch.entity.UserInfo;
import com.cays.myresearch.ui.HeadControlPanel;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Response;

public class PostQuestionActivity extends AppCompatActivity implements View.OnClickListener,
    HeadControlPanel.HeadPanelCallback{
    private EditText titleText,contentText;
    private Button submitBtn,cancelBtn;
    private HeadControlPanel postQuestionHeader;
    private Question changeQuestion,writeQuestionAnswer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String s1=getIntent().getStringExtra("change_question");
        String s2=getIntent().getStringExtra("write_answer");
        if(s1!=null&&!s1.isEmpty())
            changeQuestion=Constant.gson.fromJson(s1,new TypeToken<Question>(){}.getType());
        if(s2!=null&&!s2.isEmpty())
            writeQuestionAnswer=Constant.gson.fromJson(s1,new TypeToken<Question>(){}.getType());
        setContentView(R.layout.activity_post_question);
        if (getSupportActionBar()!=null){getSupportActionBar().hide();}
        titleText=(EditText) findViewById(R.id.post_question_title);
        contentText=(EditText) findViewById(R.id.post_question_content);
        submitBtn=(Button)findViewById(R.id.post_submit_btn);submitBtn.setOnClickListener(this);
        cancelBtn=(Button)findViewById(R.id.post_cancel_btn);cancelBtn.setOnClickListener(this);
        initView();
    }
    private void initView(){
        if(postQuestionHeader==null){
            postQuestionHeader=(HeadControlPanel)findViewById(R.id.post_question_header);
            postQuestionHeader.initHeadPanel();
            postQuestionHeader.setHeadPanelCallback(this);
        }
        postQuestionHeader.setLeftImage(R.drawable.ic_back);
        if (changeQuestion!=null){
            postQuestionHeader.setMiddleTitle("修改问题");
        }else if (writeQuestionAnswer!=null){
            postQuestionHeader.setMiddleTitle("写问题回答");
        }else {
            postQuestionHeader.setMiddleTitle("发布问题");
        }
        postQuestionHeader.setRightTitle("");
        if (changeQuestion!=null){
            titleText.setText(changeQuestion.getTitle());
            contentText.setText(changeQuestion.getContent());
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.post_submit_btn:
                String title=titleText.getText().toString(),context=contentText.getText().toString();
                if (checkQuestion(title,context)&&changeQuestion==null&&writeQuestionAnswer==null){
                    sendQuestion(title,context,"add");
                }else if(checkQuestion(title,context)&&changeQuestion!=null){
                    sendQuestion(title,context,"change");
                }else if(checkQuestion(title,context)&&writeQuestionAnswer!=null){
                    writeMyAnswer(title,context,writeQuestionAnswer);
                }
                break;
            case R.id.post_cancel_btn:finish();break;
            default:break;
        }
    }
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what==1){
                String s=(String) msg.obj;
                ResponseInfo responseInfo=Constant.gson.fromJson(s.split("~")[0],
                        new TypeToken<ResponseInfo>(){}.getType());
                Toast.makeText(getApplicationContext(),""+responseInfo.getResponseInfo(),
                        Toast.LENGTH_SHORT).show();
                if (responseInfo.getResponseCode()==200){
                    finish();
                }
            }else if (msg.what==0){
                Toast.makeText(getApplicationContext(),"未知错误",
                        Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    });
    //发送问题信息
    private void sendQuestion(String title,String content,String a_c){

        LoginAction loginAction=new LoginAction();
        UserInfo userInfo=loginAction.getUserInfo(getApplicationContext());
        Student student=Constant.gson.fromJson(userInfo.getUser(),
                new TypeToken<Student>(){}.getType());
        Question question=student.issueQuestion(title,content);
        final String url;
        final MultipartBody.Builder builder=new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        if (a_c.equals("add")){
            url=Constant.URL+"question/add";
            builder.addFormDataPart("add_question",Constant.gson.toJson(question));
        }else{
            if (changeQuestion==null||!userInfo.getName().equals(changeQuestion.getName())){
                Toast.makeText(this,"不是作者无权修改",Toast.LENGTH_SHORT).show();
                return;
            }
            url=Constant.URL+"question/change";
            builder.addFormDataPart("change_question",Constant.gson.toJson(question));
        }
       HttpUtil.sendHttpRequest(url,builder,handler,1,0);
    }
    //检测合法
    private boolean checkQuestion(String title,String context){
        if (title.isEmpty()||context.isEmpty()){
            Toast.makeText(this,"问题有误",Toast.LENGTH_LONG).show();
            return false;
        }
        LoginAction loginAction=new LoginAction();
        if(loginAction.hasUserInfo(getApplicationContext())){
            UserInfo userInfo=loginAction.getUserInfo(getApplicationContext());
            if(userInfo.getType()==Constant.user_student){
                return true;
            }else{
                Toast.makeText(getApplicationContext(),"用户权限不正确",Toast.LENGTH_SHORT).show();
                return false;
            }
        }else{
            Toast.makeText(getApplicationContext(),"未登录",Toast.LENGTH_SHORT).show();
            return false;
        }
    }
    //写回答
    private void writeMyAnswer(String title,String context,Question question){
        LoginAction loginAction=new LoginAction();
        if(!loginAction.hasUserInfo(getApplicationContext())) {
            Toast.makeText(getApplicationContext(),"未登录",Toast.LENGTH_SHORT).show();
            return;
        }
        UserInfo userInfo=loginAction.getUserInfo(getApplicationContext());
        if(userInfo.getType()!=Constant.user_teacher){
            Toast.makeText(getApplicationContext(),"用户权限不正确",Toast.LENGTH_SHORT).show();
            return;
        }
        Teacher teacher=Constant.gson.fromJson(userInfo.getUser(),
                new TypeToken<Teacher>(){}.getType());
        QuestionAnswer answer=teacher.answerQuestion(title,context,question);
        final String url=Constant.URL+"question/answer";
        final MultipartBody.Builder builder=new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("answer_question",Constant.gson.toJson(question));
        HttpUtil.sendHttpRequest(url,builder,handler,1,0);
    }
    @Override
    public void onHeadPanelClick(int itemId) {
        switch (itemId){
            case Constant.btn_left_title:
                finish();
                break;
            case Constant.btn_middle_title:
                break;
            case Constant.btn_right_title:
                break;
            default:break;
        }
    }
}
